package com.yksj.healthtalk.ui.salon;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONTokener;
import org.universalimageloader.core.ImageLoader;

import sfs2x.client.core.SFSEvent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.yksj.healthtalk.adapter.salonInfoTypeAdapter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.ImageGalleryActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.comm.SearchByTagActivity;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.GroupInfoEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.chatting.ChatActivity;
import com.yksj.healthtalk.ui.salon.SalonSelectPaymentOptionActivity.OnBuyTicketHandlerListener;
import com.yksj.healthtalk.ui.setting.SettingWebUIActivity;
import com.yksj.healthtalk.utils.ActivityUtils;
import com.yksj.healthtalk.utils.CollectUtils;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.SalonHttpUtil;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * @ClassName: SalonInformationActivity
 * @Description: 话题资料
 * 
 * @date 2013-1-10 上午8:14:21
 */
public class SalonInformationActivity extends BaseFragmentActivity implements
		OnClickListener, OnItemClickListener, OnBuyTicketHandlerListener {
	private Button titleBackBtn;// 返回按钮
	private ToggleButton mMessageToggleBtn;// 是否s接受消息推送按钮
	private ToggleButton mOpenInfoToggleBtn;// 是否对消息厅开放按钮
	private GroupInfoEntity mSalonEntity;
	private EditText mSalonNameEt;// 话题name
	private EditText mSalonSignature;// 话题签名
	private ImageView mV;// 话题等级
	private ImageView mHead;
	private ImageView mIsDoctorSalonIv;// 是否是医师话题
	private ImageView mIsPaySalonIv;// 是否是付费的话题
	protected String groupId;
	private final int WHAT_FAILE = -1;
	private final int WHAT_SUCC = 1;
	private String imagePath;// 头像路径
	private LinearLayout mTalkLin;
	private LinearLayout mUnfollowLin;
	private GridView infoTypeGridView;
	private BaseAdapter mAdapter;
	private ImageLoader mImageLoader;
	private LinearLayout creatorLin;// 创建者信息
	String[] names;
	String[] ids;

	private ImageView att_iv;
	private TextView att_tv;
	private int position;// 列表点击进入 列表的 position
	private AppData mAppData;
	private ChatUserHelper chatUserHelper;
	private Boolean isReleaseSystemMessageState;
	private Boolean isInceptMessageState;
	private LinearLayout salonSettingLinearLayout;// 话题设置分割线
	private RelativeLayout inceptMessageSettingRelativeLayout;// 话题消息推送布局
	private LinearLayout openMessageSettingLinearLayout; // 是否对消息厅布局
	private TextView infoOrServer;
//	private View line;
	private boolean defaultState;// 刚开始的关注状态
	
	BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_GROUP_NOT)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(getApplicationContext(),R.string.groupNewFail);
				} else {
					mSalonEntity.setSalonAttention(false);
					ToastUtil.showShort(getApplicationContext(), "取消关注成功");
					setSalonSettingVisible(false);
					// 判断最近联系话题里面是否有该对象
					if (mAppData.getLatelyGroupIdList().contains(
							mSalonEntity.getId())) {
						CollectUtils.updateGroupRecent(chatUserHelper,
								mSalonEntity, SmartFoxClient.getLoginUserId());
						HTalkApplication.getAppData().updateCacheInfomation(
								mSalonEntity);
					} else {
						// 联系人不存在该联系人 则从数据库中删除该群
						HTalkApplication.getAppData().removeCacheInfomation(
								mSalonEntity);
						CollectUtils.deleteSalon(chatUserHelper,
								mSalonEntity.getId());
						mAppData.getInterestGroupIdList().remove(
								mSalonEntity.getId());
					}
				}
			} else if (action.equals(MessagePushService.ACTION_COLLECT_GROUP)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(getApplicationContext(),
							R.string.groupNewFail);
				} else {
					mSalonEntity.setSalonAttention(true);
					ToastUtil.showShort(getApplicationContext(), "关注成功");
					setSalonSettingVisible(true);
					// //判断最近联系话题里面是否有该对象
					if (mAppData.getLatelyGroupIdList().contains(
							mSalonEntity.getId())) {
						CollectUtils.updateGroupRecent(chatUserHelper,
								mSalonEntity, SmartFoxClient
										.getSmartFoxClient().getUserId());
						HTalkApplication.getAppData().updateCacheInfomation(
								mSalonEntity);
					} else {
						chatUserHelper.saveGroupInfo(context, mSalonEntity,
								mSalonEntity.getId());
						mAppData.getInterestGroupIdList().add(0,
								mSalonEntity.getId());
						HTalkApplication.getAppData().updateCacheInfomation(
								mSalonEntity);
					}
				}
			} else if (action.equals(SFSEvent.CONNECTION_LOST)) {
				SmartFoxClient.getSmartFoxClient().doConnecion();
			}
			// 是取消关注还是关注
			if (mSalonEntity.isSalonAttention() == true) {
				att_iv.setImageResource(R.drawable.person_quxiao_guanzhu);
				att_tv.setText(R.string.cancelCollect);
			} else {
				att_iv.setImageResource(R.drawable.person_guanzhu);
				att_tv.setText(R.string.atention);
			}
		}

	};
	private Button titleRightBtn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		setContentView(R.layout.salon_information);
		initWidget();
		initData(getIntent());
	}

	/**
	 * @Title: initData
	 * @Description: 初始化数据
	 * @param
	 * @return void
	 * @throws
	 */
	private void initData(Intent intent) {
		mAppData = HTalkApplication.getAppData();
		chatUserHelper = ChatUserHelper.getInstance();
		if (intent.hasExtra("entity")) {
			mSalonEntity = (GroupInfoEntity) intent.getParcelableExtra("entity");
			initInfo();
		} else if (intent.hasExtra("id")) {
			HttpRestClient.doHttpSalonToId(SmartFoxClient.getLoginUserId(),getIntent().getExtras().getString("id"),
					new ObjectHttpResponseHandler(this) {
						@Override
						public Object onParseResponse(String content) {
							GroupInfoEntity entity = null;
							if ("N".equals(content)) {
								ToastUtil.showShort(getApplicationContext(),content);
							} else {
								entity = SalonHttpUtil.jsonAnalysisSalonEntity(content).get(0);
							}
							return entity;
						}

						@Override
						public void onSuccess(int statusCode, Object response) {
							super.onSuccess(statusCode, response);
							if (response != null&& response instanceof GroupInfoEntity) {
								mSalonEntity = (GroupInfoEntity) response;
							}
							initInfo();
						}
					});
		}
	}

	private void initInfo() {
		if (mSalonEntity == null) {
			ToastUtil.showShort(getApplicationContext(), R.string.value_error);
			return;
		}
		titleRightBtn.setBackgroundResource(R.drawable.diamond);
		// 关注状态
		defaultState = mSalonEntity.isSalonAttention();
		// 判断是否显示话题设置
		groupId = mSalonEntity.getId();
		// 判断是否是商务话题
		if (mSalonEntity.getMerchantId().equals("")) {
			infoOrServer.setText(R.string.salon_creator_infomation);
		} else {
			infoOrServer.setText(R.string.server_list);
		}

		if (HTalkApplication.getAppData().getInterestGroupIdList().contains(groupId)) {
			setSalonSettingVisible(true);
		} else {
			setSalonSettingVisible(false);
		}
		// 话题名
		mSalonNameEt.setText(mSalonEntity.getName() != null ? mSalonEntity
				.getName() : "");
		TextView mTitleLable = (TextView) findViewById(R.id.title_lable);
		mTitleLable.setText(mSalonEntity.getName() != null ? mSalonEntity.getName() : "");
		// 描述
		mSalonSignature.setText(mSalonEntity.getRecordDesc() != null ? mSalonEntity.getRecordDesc() : "");
		// 消息推送
		mMessageToggleBtn.setChecked(mSalonEntity.isInceptMessage() == true ? true: false);
		isInceptMessageState = mMessageToggleBtn.isChecked();
		// 是否将消息发布到消息厅
		mOpenInfoToggleBtn.setChecked(mSalonEntity.getIsReleaseSystemMessage() == true ? true: false);
		isReleaseSystemMessageState = mOpenInfoToggleBtn.isChecked();
		// 是否是医师话题
		mIsDoctorSalonIv.setVisibility(mSalonEntity.isSalon() ? View.VISIBLE
				: View.GONE);
		// 是否是收费话题
		mIsPaySalonIv.setVisibility(mSalonEntity.isCharge() ? View.VISIBLE: View.GONE);
		// 话题的等级
		int level;
		if ((level = Integer.valueOf(mSalonEntity.getGroupLevel())) > 0) {
			mV.getDrawable().setLevel(level);
		} else {
			mV.setVisibility(View.GONE);
		}

		// 话题头像
		mImageLoader = ImageLoader.getInstance();
		mImageLoader.displayImage("4",mSalonEntity.getNormalHeadIcon(), mHead);
		// 话题类型描述
		String InfoLayName = mSalonEntity.getInfoLayName();
		String InfoLayIds = mSalonEntity.getInfoId();
		if (InfoLayName.equals("")) {
		} else {
			names = InfoLayName.split(",");
			ids = InfoLayIds.split(",");
			List<String> list = Arrays.asList(names);
			mAdapter = new salonInfoTypeAdapter(this, list);
			infoTypeGridView.setAdapter(mAdapter);
			infoTypeGridView.setOnItemClickListener(this);
		}
		// 是取消关注还是关注
		if (mSalonEntity.isSalonAttention() == true) {
			att_iv.setImageResource(R.drawable.person_quxiao_guanzhu);
			att_tv.setText("取消关注");
		} else {
			att_iv.setImageResource(R.drawable.person_guanzhu);
			att_tv.setText("关注");
		}
	}

	// 注册广播
	@Override
	public void onStart() {
		IntentFilter filter = new IntentFilter(MessagePushService.ACTION_GROUPLIST);
		// 取消关注的过滤器
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP_NOT);
		filter.addAction(MessagePushService.ACTION_JOIN_GROUP);
		filter.addAction(MessagePushService.ACTION_MESSAGE);

		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP);
		registerReceiver(receiver, filter);
		super.onStart();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		initData(intent);
	}

	@Override
	protected void onStop() {
		unregisterReceiver(receiver);
		super.onStop();
	}

	/**
	 * @Title: initWidget
	 * @Description: 初始化空间
	 * @param
	 * @return void
	 * @throws
	 */
	private void initWidget() {
		titleBackBtn = (Button) findViewById(R.id.title_back);
		titleRightBtn = (Button) findViewById(R.id.title_right);
		mMessageToggleBtn = (ToggleButton) findViewById(R.id.message_setting_toggleBtn);
		mOpenInfoToggleBtn = (ToggleButton) findViewById(R.id.info_toggleBtn);
		mSalonNameEt = (EditText) findViewById(R.id.info_name);
		mSalonSignature = (EditText) findViewById(R.id.info_desc);
		mV = (ImageView) findViewById(R.id.v);
		mIsDoctorSalonIv = (ImageView) findViewById(R.id.isdoctor_iv);
		mIsPaySalonIv = (ImageView) findViewById(R.id.ispay_iv);
		mTalkLin = (LinearLayout) findViewById(R.id.talk_lin);
		mUnfollowLin = (LinearLayout) findViewById(R.id.unfollow_lin);
		infoTypeGridView = (GridView) findViewById(R.id.info_type_gv);
		creatorLin = (LinearLayout) findViewById(R.id.creator_lin);
		att_iv = (ImageView) findViewById(R.id.att_iv);
		att_tv = (TextView) findViewById(R.id.att_tv);
		mHead = (ImageView) findViewById(R.id.info_head);
		salonSettingLinearLayout = (LinearLayout) findViewById(R.id.salon_setting);
		inceptMessageSettingRelativeLayout = (RelativeLayout) findViewById(R.id.incept_message_setting);
		openMessageSettingLinearLayout = (LinearLayout) findViewById(R.id.open_message_setting);
		infoOrServer = (TextView) findViewById(R.id.info_or_list);
//		line = findViewById(R.id.line);
		// 设置监听器
		titleBackBtn.setOnClickListener(this);
		mTalkLin.setOnClickListener(this);
		mUnfollowLin.setOnClickListener(this);
		creatorLin.setOnClickListener(this);
		mHead.setOnClickListener(this);
		titleRightBtn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.unfollow_lin://取消关注
			if (mSalonEntity.isSalonAttention()) {
				SmartFoxClient.sendStrRequest(SmartFoxClient.RequestCode.COLLECT_GROUP_NOT,
						mSalonEntity.getId());
			} else {
				SmartFoxClient.sendStrRequest(SmartFoxClient.RequestCode.COLLECT_GROUP,
						mSalonEntity.getId());
			}
			break;
		case R.id.talk_lin://对话
			SalonHttpUtil.onItemClick(getApplicationContext(), this,getSupportFragmentManager(), mSalonEntity, true);
			break;
		// 创建者信息
		case R.id.creator_lin:
			// 判断是否是商务话题
			if (mSalonEntity.getMerchantId().equals("")) {
				ActivityUtils.startUserInfoActivity(this,getSupportFragmentManager(),mSalonEntity.getCreateCustomerID());
			} else {//服务人员列表
				HttpRestClient.doHttpFindCustomersByCenterGroup(
						mSalonEntity.getId(), SmartFoxClient.getLoginUserId(),
						mSalonEntity.getMerchantId(),
						new ObjectHttpResponseHandler(this) {
							@Override
							public Object onParseResponse(String content) {
								JSONTokener tokener = new JSONTokener(content);
								Object object = null;
								try {
									object = tokener.nextValue();
								} catch (JSONException e) {
									e.printStackTrace();
								}
								if(object instanceof JSONArray){
									 JSONArray array = (JSONArray)object;
									if (array.length() == 0) {
										SalonInformationActivity.this
										.runOnUiThread(new Runnable() {
											@Override
											public void run() {
												ToastUtil.showShort(getApplicationContext(),R.string.expert_not_online);
											}
										});
									}else {
										return FriendHttpUtil.jsonAnalysisFriendEntity(content, true);
									}
								}
								return null;
							}
							@Override
							public void onSuccess(int statusCode,
									Object response) {
								if (response != null) {
									ArrayList<CustomerInfoEntity> entities = (ArrayList<CustomerInfoEntity>) response;
									Intent intent = new Intent(getApplicationContext(),ServiceMembersActivity.class);
									intent.putParcelableArrayListExtra("list",entities);
									startActivity(intent);
								}
								super.onSuccess(statusCode, response);
							}
						});
			}

			break;
		case R.id.info_head:
			if (mSalonEntity.getBigHeadIcon() == null|| "".equals(mSalonEntity.getBigHeadIcon())) {
				return;
			}
			Intent intent = new Intent(this, ImageGalleryActivity.class);
			intent.putExtra(ImageGalleryActivity.URLS_KEY,new String[] { mSalonEntity.getBigHeadIcon() });
			intent.putExtra(ImageGalleryActivity.TYPE_KEY, 0);// 0,1单个,多个
			intent.putExtra("type", 1);
			startActivity(intent);
			break;
		case R.id.title_right:
			intent = new Intent(this, SettingWebUIActivity.class);
			intent.putExtra("TextSize", 40);
			intent.putExtra("url","http://www.h-tlk.com/sms_web/Salon_Level.html");
			intent.putExtra("title", "话题等级介绍");
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (ids != null && ids.length != 0) {
			GroupInfoEntity mGroupInfoEntity = new GroupInfoEntity();
			mGroupInfoEntity.setInfoId(ids[position]);
			mGroupInfoEntity.setInfoLayName(names[position]);
			mGroupInfoEntity.setCreateCustomerID(SmartFoxClient.getLoginUserId());
			Intent intent = new Intent(getApplicationContext(),SearchByTagActivity.class);
			intent.putExtra("entity", mGroupInfoEntity);
			startActivity(intent);
		}
	}

	/**
	 * 判断个人资料是否修改过
	 * 
	 * @return
	 */
	public Boolean isStateChanged() {
		if (isInceptMessageState == mMessageToggleBtn.isChecked()
				&& isReleaseSystemMessageState == mOpenInfoToggleBtn
						.isChecked()) {
			return false;
		}
		return true;
	}

	/**
	 * 判断是否显示话题设置
	 * 
	 * @param b
	 *            true 显示
	 */
	public void setSalonSettingVisible(Boolean b) {
		if (b) {
//			line.setVisibility(View.VISIBLE);
			salonSettingLinearLayout.setVisibility(View.VISIBLE);
			openMessageSettingLinearLayout.setVisibility(View.VISIBLE);
			inceptMessageSettingRelativeLayout.setVisibility(View.VISIBLE);
		} else {
//			line.setVisibility(View.INVISIBLE);
			salonSettingLinearLayout.setVisibility(View.INVISIBLE);
			openMessageSettingLinearLayout.setVisibility(View.INVISIBLE);
			inceptMessageSettingRelativeLayout.setVisibility(View.INVISIBLE);
		}
	}

	@Override
	public void onBackPressed() {
		if (isStateChanged()) {
			HttpRestClient.doHttpUpdateGroupInceptMsg(SmartFoxClient
					.getSmartFoxClient().getUserId(), mSalonEntity.getId(),
					mMessageToggleBtn.isChecked(), mOpenInfoToggleBtn
							.isChecked(), new AsyncHttpResponseHandler() {

						@Override
						public void onSuccess(int statusCode, String content) {
							if (content.equalsIgnoreCase("N")) {
								// ToastUtil.showShort(getApplicationContext(),
								// "修改失败~");
							} else {
								mSalonEntity.setInceptMessage(mMessageToggleBtn
										.isChecked());
								mSalonEntity
										.setIsReleaseSystemMessage(mOpenInfoToggleBtn
												.isChecked());
							}
							super.onSuccess(statusCode, content);
						}

						@Override
						public void onFinish() {
							HTalkApplication.getAppData().updateCacheInfomation(mSalonEntity);
							isAttStateChange();
							finish();
							super.onFinish();
						}
					});
		} else {
			isAttStateChange();
			finish();
		}

	}

	/**
	 * 关注状态是否改变
	 */
	private void isAttStateChange() {
		if (defaultState != mSalonEntity.isSalonAttention()) {
			Intent i = getIntent();
			if (i.hasExtra("position")
					&& i.getExtras().getInt("position") != -1) {
				position = i.getExtras().getInt("position");
				i.putExtra("mSalonInformationEntity", mSalonEntity);
				i.putExtra("position", position);
				this.setResult(RESULT_OK, i);
				HTalkApplication.getAppData().updateCacheInfomation(
						mSalonEntity);
			}
		}
	}

	@Override
	public void onTicketHandler(String state, GroupInfoEntity entity) {
		// TODO Auto-generated method stub
		if ("0".equals(state)) {
//			ToastUtil.showShort(getApplicationContext(), "多美币不足");
		} else if ("-1".equals(state)) {
			ToastUtil.showShort(getApplicationContext(), "服务器出错");
		} else {
			Intent intent1 = new Intent();
			intent1.putExtra(ChatActivity.KEY_PARAME, entity);
			intent1.setClass(getApplicationContext(), ChatActivity.class);
			startActivity(intent1);
		}
	}

}
